/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package my.cbr.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.UIManager;
import jcolibri.cbrcore.CBRCase;
import jcolibri.method.retrieve.RetrievalResult;
import jcolibri.util.FileIO;
import my.cbr.application.CBRApplication;
import my.cbr.casedescriptions.CaseDescription;
import my.cbr.casedescriptions.CaseSolution;
import my.cbr.database.model.AquacultureProdUnit;
import my.cbr.database.model.FishDeath;
import my.cbr.utils.Utility;

/**
 *
 * @author Marte
 */
public class ResultDialog extends JDialog{
    
    private JLabel backgroundImage;

    private JLabel caseId;
    private JLabel sending;
    private JLabel recieving;
    private JLabel site;
    private JLabel date;
    private JLabel starvationDays;
    private JLabel vaccine;
    private JLabel hatchery;
    private JLabel origin;
    private JLabel capacity;
    private JLabel individCount;
    private JLabel currentTemp;
    private JLabel tempTrend;
    private JLabel currentOxygen;
    private JLabel oxyTrend;
    private JLabel risk;
    private JLabel percentageDeath;
    private JLabel aggregatedCount;

    private ArrayList<RetrievalResult> cases;
    private int currentCase;


    public ResultDialog(JFrame parent)
    {
        super(parent, true);
        configureFrame();
    }

    private void configureFrame()
    {
        try{
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
	}catch (Exception e1){}


        backgroundImage = new JLabel();
        backgroundImage.setIcon(new ImageIcon(FileIO.findFile("my/cbr/gui/images/retrievedCases.png")));
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(backgroundImage, BorderLayout.WEST);

        JLabel label;

        JPanel panel = new JPanel();
        panel.setLayout(new SpringLayout());
        panel.add(label = new JLabel("Description"));
        label.setFont(label.getFont().deriveFont(Font.BOLD));
        panel.add(label = new JLabel());

        panel.add(new JLabel("Sending production units"));
        panel.add(sending = new JLabel());

        panel.add(new JLabel("Recieving production unit"));
        panel.add(recieving = new JLabel());

        panel.add(new JLabel("Aquaculture Site"));
        panel.add(site = new JLabel());

        panel.add(new JLabel("Capacity of site"));
        panel.add(capacity = new JLabel());

        panel.add(new JLabel("Individ Count in sending unit"));
        panel.add(individCount = new JLabel());

        panel.add(new JLabel("Operation Date"));
        panel.add(date = new JLabel());

        panel.add(new JLabel("Number of startvation days"));
        panel.add(starvationDays = new JLabel());

        panel.add(new JLabel("Vaccines"));
        panel.add(vaccine = new JLabel());

        panel.add(new JLabel("Hatcheries"));
        panel.add(hatchery = new JLabel());

        panel.add(new JLabel("Species Origins"));
        panel.add(origin = new JLabel());

        panel.add(new JLabel("Current Temperature"));
        panel.add(currentTemp = new JLabel());

        panel.add(new JLabel("Temperature Trend"));
        panel.add(tempTrend = new JLabel());

        panel.add(new JLabel("Current Oxygen Level"));
        panel.add(currentOxygen = new JLabel());

        panel.add(new JLabel("Oxygen Trend"));
        panel.add(oxyTrend = new JLabel());


        panel.add(label = new JLabel("Solution"));
        label.setFont(label.getFont().deriveFont(Font.BOLD));
        panel.add(label = new JLabel());

        panel.add(new JLabel("Risk"));
        panel.add(risk = new JLabel());
        
        panel.add(new JLabel("Percentage dead"));
        panel.add(percentageDeath = new JLabel());
        
        panel.add(new JLabel("Aggregated Count"));
        panel.add(aggregatedCount = new JLabel());

        
        Utils.makeCompactGrid(panel,
		                19, 2, //rows, cols
		                6, 6,        //initX, initY
		                30, 10);       //xPad, yPad

        JPanel casesPanel = new JPanel();
        casesPanel.setLayout(new BorderLayout());
        casesPanel.add(panel, BorderLayout.CENTER);

        JPanel casesIterPanel = new JPanel();
        casesIterPanel.setLayout(new FlowLayout());
        JButton prev = new JButton("<<");
        casesIterPanel.add(prev);
        casesIterPanel.add(caseId = new JLabel("Case id"));
        JButton follow = new JButton(">>");
        casesIterPanel.add(follow);

        prev.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
                        currentCase = (currentCase+cases.size()-1) % cases.size();
                        showCase();
                }
	});

		follow.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				currentCase = (currentCase+1) % cases.size();
				showCase();
			}
		});

		casesPanel.add(casesIterPanel, BorderLayout.NORTH);


		JPanel panelAux = new JPanel();
		panelAux.setLayout(new BorderLayout());
		panelAux.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

		panelAux.add(casesPanel,BorderLayout.NORTH);

		JPanel buttons = new JPanel();
		buttons.setLayout(new BorderLayout());

		JButton graph = new JButton("Visualize causes of death");
                graph.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {

                        RetrievalResult rr = cases.get(currentCase);
                        CBRCase _case = rr.get_case();
                        CaseSolution sol = (CaseSolution) _case.getSolution();
                        List<FishDeath> fishDeaths = sol.getFishdeath();
                        JDialog graphDialog = new JDialog(ResultDialog.this);
                        graphDialog.setName("Visualization of deaths");
                        graphDialog.add(Utils.createFishDeathChart(Utility.getAggregatedCount(fishDeaths)));
                        graphDialog.pack();
                        graphDialog.setVisible(true);

                    }
                });
                buttons.add(graph, BorderLayout.CENTER);

                JButton ok = new JButton("Next >>");
		ok.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				next();
			}
		});
		buttons.add(ok,BorderLayout.EAST);
		JButton exit = new JButton("Exit");
		exit.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				try {
					CBRApplication.getInstance().postCycle();
				} catch (Exception ex) {
					org.apache.commons.logging.LogFactory.getLog(CBRApplication.class).error(ex);
				}
				System.exit(-1);
			}
		});
		buttons.add(exit,BorderLayout.WEST);

		panelAux.add(buttons, BorderLayout.SOUTH);
		this.getContentPane().add(panelAux, BorderLayout.CENTER);

		/**********************************************************/


		this.pack();
		this.setSize(650, this.getHeight());
		//this.setResizable(false);
		Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
		setBounds((screenSize.width - this.getWidth()) / 2,
			(screenSize.height - this.getHeight()) / 2,
			getWidth(),
			getHeight());
    }

    void next()
    {
        this.setVisible(false);
    }

    public void showCases(Collection<RetrievalResult> eval, Collection<CBRCase> selected){

        cases = new ArrayList<RetrievalResult>();
	for(RetrievalResult rr: eval)
            if(selected.contains(rr.get_case()))
                cases.add(rr);
	currentCase = 0;
	showCase();

    }

    
    private void showCase(){

       RetrievalResult rr = cases.get(currentCase);
       double sim = rr.getEval();

       CBRCase _case = rr.get_case();
       this.caseId.setText(_case.getID().toString()+" -> "+sim+" ("+(currentCase+1)+"/"+cases.size()+")");

       CaseDescription desc = (CaseDescription) _case.getDescription();
       this.sending.setText(desc.getSendingProdUnits().toString());
       this.recieving.setText(desc.getReceivingProdUnit().toString());
       this.site.setText(desc.getAquacultureSite().getSiteID()+"");
       this.capacity.setText(desc.getAquacultureSite().getCapacity()+"");
       String count = "";
       String days = "";
            for(AquacultureProdUnit prodSending : desc.getSendingProdUnits())
            {
                count += prodSending.getIndividCount()+"  ";
                days += prodSending.getStarvationDays()+"  ";
            }
       this.individCount.setText(count);
       this.starvationDays.setText(days);
       this.date.setText(desc.getDateTime().toString());
       this.vaccine.setText(Utility.getString(desc.getReceivingProdUnit().getVaccine().toArray()));
       this.hatchery.setText(Utility.getString(desc.getReceivingProdUnit().getHatcheryCompanyID().toArray()));
       this.origin.setText(Utility.getString(desc.getReceivingProdUnit().getSpeciesOrigin().toArray()));
       this.currentTemp.setText(desc.getTemperature().getCurrentInstance().getValue()+" C");
       this.tempTrend.setText(desc.getTemperature().getTrend());
       this.currentOxygen.setText(desc.getOxygen().getCurrentInstance().getValue()+" %");
       this.oxyTrend.setText(desc.getOxygen().getTrend());


       CaseSolution sol = (CaseSolution) _case.getSolution();
       this.risk.setText(sol.getRisk());
       this.percentageDeath.setText(sol.getDeathRatio()*100+"%");
//       this.percentageDeath.setToolTipText("The percentage is taken from the total death on this production unit compared "
//               + "to the individ count on the sending units. The amount of fish sent is however not the same as individ count. The "
//               + "death percentage could therefore be higher than what is displayed.");
       this.aggregatedCount.setText(sol.getAggregatedCount()+"");
                
	}

    public static void main(String[] args) {
		ResultDialog qf = new ResultDialog(null);
		qf.setVisible(true);
		System.out.println("Bye");
	}


}
